import { useRoute } from 'vue-router';
import { useAuthStore } from '@/store/modules/auth';

const { VITE_AUTH_BUTTON_MODE = 'route_meta' } = import.meta.env;

export function useAuth() {
  const authStore = useAuthStore();

  const route = useRoute();

  const hasAuthModelPermissionMap: Record<Env.AuthButtonMode, string[]> = {
    route_meta: route?.meta.permissions ?? [],
    user_info: authStore.userInfo.permissions ?? []
  };

  function hasAuth(codes: string | string[]) {
    if (!authStore.isLogin) {
      return false;
    }

    const permissions = hasAuthModelPermissionMap[VITE_AUTH_BUTTON_MODE as Env.AuthButtonMode];
    if (typeof codes === 'string') {
      return permissions.includes(codes);
    }

    return codes.some(code => permissions.includes(code));
  }

  function userInfo(): Api.Auth.UserInfo | null {
    if (!authStore.isLogin) {
      return null;
    }
    return authStore.userInfo;
  }

  function currentOrgPosition(): Api.Auth.OrgPosition | null {
    if (!authStore.isLogin) {
      return null;
    }

    if (!authStore.userInfo.currentOrgPosition) {
      if (authStore.userInfo.orgPositions.length === 0) {
        window.$message?.error('您尚未设置有效的组织岗位信息');
      } else if (authStore.userInfo.orgPositions.length > 1) {
        window.$message?.error('系统为您设置了多个组织岗位，无法确认您当前的组织身份');
      }
      return null;
    }

    return authStore.userInfo.currentOrgPosition;
  }

  return {
    hasAuth,
    userInfo,
    currentOrgPosition
  };
}
